<!--
  修复版预览组件 - 解决内存泄漏问题
  主要修复：
  1. 统一使用ResourceManager管理定时器和事件监听器
  2. 确保组件卸载时清理所有资源
  3. 修复WebSocket连接管理
  4. 移除全局变量污染
-->
<template>
  <div class="mt-preview-container">
    <!-- 预览内容 -->
    <div ref="previewRef" class="preview-content">
      <!-- 原有的预览组件内容 -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useResourceManager } from '@/utils/resource-manager';
import { unifiedWebSocketService } from '@/services/unified-websocket';

// 使用资源管理器
const resourceManager = useResourceManager('MTPreview');

// 响应式引用
const previewRef = ref<HTMLElement>();

// 预览相关状态
const previewState = ref({
  isFullscreen: false,
  scale: 1,
  isResizing: false
});

// WebSocket连接状态
const wsConnections = ref(new Map<string, string>());

/**
 * 初始化预览组件
 */
const initPreview = () => {
  console.log('初始化预览组件');

  // 设置窗口大小调整监听器
  setupResizeListener();

  // 初始化WebSocket连接
  initWebSocketConnections();

  // 设置全局API（使用安全的方式）
  setupGlobalAPI();
};

/**
 * 设置窗口大小调整监听器
 */
const setupResizeListener = () => {
  let resizeTimer: number | null = null;

  const handleResize = () => {
    previewState.value.isResizing = true;

    // 清除之前的定时器
    if (resizeTimer) {
      resourceManager.clearTimer(resizeTimer);
    }

    // 防抖处理
    resizeTimer = resourceManager.setTimeout(() => {
      previewState.value.isResizing = false;
      updatePreviewScale();
      resizeTimer = null;
    }, 300);
  };

  resourceManager.addEventListener(window, 'resize', handleResize);
};

/**
 * 更新预览缩放
 */
const updatePreviewScale = () => {
  if (!previewRef.value) return;

  const container = previewRef.value.parentElement;
  if (!container) return;

  const containerRect = container.getBoundingClientRect();
  const contentRect = previewRef.value.getBoundingClientRect();

  const scaleX = containerRect.width / contentRect.width;
  const scaleY = containerRect.height / contentRect.height;
  const scale = Math.min(scaleX, scaleY, 1);

  previewState.value.scale = scale;
  previewRef.value.style.transform = `scale(${scale})`;
};

/**
 * 初始化WebSocket连接
 */
const initWebSocketConnections = () => {
  // 注册WebSocket服务作为资源
  resourceManager.registerResource(
    'websocket-service',
    unifiedWebSocketService,
    () => {
      // 清理所有WebSocket连接
      console.log('清理WebSocket连接');
      // unifiedWebSocketService会在自己的destroy方法中处理清理
    },
    'websocket'
  );

  // 设置全局消息处理器
  unifiedWebSocketService.setGlobalMessageHandler((message) => {
    handleWebSocketMessage(message);
  });
};

/**
 * 处理WebSocket消息
 */
const handleWebSocketMessage = (message: any) => {
  try {
    console.log('收到WebSocket消息:', message);
    // 处理消息逻辑
  } catch (error) {
    console.error('处理WebSocket消息失败:', error);
  }
};

/**
 * 设置全局API（安全版本）
 */
const setupGlobalAPI = () => {
  // 创建命名空间避免全局污染
  const mtPreviewAPI = {
    setItemAttr: (id: string, key: string, val: any) => {
      // 实现设置属性逻辑
      console.log('设置属性:', { id, key, val });
    },

    getItemAttr: (id: string, key: string) => {
      // 实现获取属性逻辑
      console.log('获取属性:', { id, key });
      return null;
    },

    getRealtimeData: (pointId: string) => {
      // 实现获取实时数据逻辑
      console.log('获取实时数据:', pointId);
      return null;
    }

    // 其他API方法...
  };

  // 注册API到资源管理器
  resourceManager.registerResource('global-api', mtPreviewAPI, () => {
    // 清理全局API
    try {
      delete (window as any).$mtPreviewAPI;
    } catch (error) {
      console.warn('清理全局API失败:', error);
    }
  });

  // 安全地设置到全局
  (window as any).$mtPreviewAPI = mtPreviewAPI;
};

/**
 * 启动实时数据模拟
 */
const startRealTimeSimulation = (interval: number = 2000) => {
  // 停止之前的模拟
  stopRealTimeSimulation();

  const timer = resourceManager.setInterval(() => {
    // 模拟实时数据更新
    console.log('更新实时数据');
  }, interval);

  // 将定时器ID存储到组件状态中
  resourceManager.registerResource('realtime-simulation', { timerId: timer }, () => {
    resourceManager.clearTimer(timer);
  });

  return timer;
};

/**
 * 停止实时数据模拟
 */
const stopRealTimeSimulation = () => {
  resourceManager.unregisterResource('realtime-simulation');
};

/**
 * 全屏切换
 */
const toggleFullscreen = async () => {
  if (!previewRef.value) return;

  try {
    if (!previewState.value.isFullscreen) {
      await previewRef.value.requestFullscreen();
      previewState.value.isFullscreen = true;
    } else {
      await document.exitFullscreen();
      previewState.value.isFullscreen = false;
    }
  } catch (error) {
    console.error('全屏切换失败:', error);
  }
};

/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  await nextTick();
  initPreview();

  // 监听全屏状态变化
  resourceManager.addEventListener(document, 'fullscreenchange', () => {
    previewState.value.isFullscreen = !!document.fullscreenElement;
  });
});

/**
 * 组件卸载时清理资源
 */
onUnmounted(() => {
  console.log('预览组件卸载，开始清理资源');

  // ResourceManager会自动清理所有注册的资源
  resourceManager.destroy();

  // 检查是否有遗漏的资源
  const leaks = resourceManager.checkForLeaks();
  if (leaks.length > 0) {
    console.warn('发现潜在的内存泄漏:', leaks);
  }
});

// 暴露给模板的方法
defineExpose({
  toggleFullscreen,
  startRealTimeSimulation,
  stopRealTimeSimulation,
  updatePreviewScale,
  getResourceStats: () => resourceManager.getStats()
});
</script>

<style scoped>
.mt-preview-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.preview-content {
  width: 100%;
  height: 100%;
  transform-origin: top left;
  transition: transform 0.3s ease;
}

.preview-content.resizing {
  transition: none;
}
</style>
